<template>
  <div class="upload">
    <div class="box">
      <el-upload
        class="upload-demo"
        drag
        action="#"
        :on-change="change"
        :auto-upload="false"
        :show-file-list="false"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip"></div>
      </el-upload>

      <div style="margin-left: 20px">
        <header>导入表格之后设置</header>
        <el-form ref="form" :model="timeForm" label-width="100px">
          <el-form-item label="考勤日期:" class="input">
            <el-input v-model="timeForm.date"></el-input>
          </el-form-item>
          <el-form-item label="文件名:" class="input">
            <el-input v-model="timeForm.name"></el-input>
          </el-form-item>
        </el-form>
      </div>

      <!-- 公司 -->
      <div class="type">
        <header>提示:上传表格之前设置,隶属公司地址</header>
        <div v-for="(item, index) in company" :key="item" class="div">
          <span>
            {{ item }}
          </span>
          <p>
            <i class="el-icon-delete" @click="deleteCompany(index)"></i>
          </p>
        </div>
        <el-button
          style="margin-top: 10px"
          type="primary"
          size="mini"
          @click="addCompany"
          >添加</el-button
        >
      </div>
      <!-- 市场人员 -->
      <div class="type">
        <header>上传之前--市场人员(拖拽可改顺序)</header>
        <draggable v-model="marketArr">
          <div v-for="(item, index) in marketArr" :key="item" class="div">
            <span>
              {{ item }}
            </span>
            <p>
              <i class="el-icon-delete" @click="deleteMarket(index)"></i>
            </p>
          </div>
        </draggable>

        <el-button
          style="margin-top: 10px"
          type="primary"
          size="mini"
          @click="addMarket"
          >添加</el-button
        >
      </div>
      <!-- 北京中心人员 -->
      <div class="type">
        <header>上传之前--北京中心(拖拽可改顺序)</header>
        <draggable v-model="centerArr">
          <div v-for="(item, index) in centerArr" :key="item" class="div">
            <span>
              {{ item }}
            </span>
            <p>
              <i class="el-icon-delete" @click="deleteCenter(index)"></i>
            </p>
          </div>
        </draggable>

        <el-button
          style="margin-top: 10px"
          type="primary"
          size="mini"
          @click="addCenter"
          >添加</el-button
        >
      </div>
      <!-- 离职人员 -->
      <div class="type">
        <header>上传之前--离职人员</header>
        <div v-for="(item, index) in fireArr" :key="item" class="div">
          <span>
            {{ item }}
          </span>
          <p>
            <i class="el-icon-delete" @click="deleteFire(index)"></i>
          </p>
        </div>

        <el-button
          style="margin-top: 10px"
          type="primary"
          size="mini"
          @click="addFire"
          >添加</el-button
        >
      </div>

      <div class="type">
        <header>上传之前--只需要打两次卡的人</header>
        <div v-for="(item, index) in arrtwoCard" :key="item" class="div">
          <span>
            {{ item }}
          </span>
          <p>
            <i class="el-icon-delete" @click="deleteArrtwoCard(index)"></i>
          </p>
        </div>

        <el-button
          style="margin-top: 10px"
          type="primary"
          size="mini"
          @click="addTwo"
          >添加</el-button
        >
      </div>
    </div>

    <el-button @click="exportFile" style="margin-top: 10px"
      >导出考勤表</el-button
    >
    <!-- <el-button @click="exportOut" style="margin-top: 10px"
      >导出外出表</el-button
    > -->
    <el-button @click="clear" style="margin-top: 10px">清空</el-button>
    <table ref="table">
      <thead>
        <tr>
          <th></th>
          <th>类别</th>
          <th>姓名</th>
          <th colspan="4">{{ timeForm.date }}</th>
        </tr>
        <tr>
          <th>时间</th>
          <th></th>
          <th></th>
          <th>9:00</th>
          <th>10:00</th>
          <th>15:00</th>
          <th>18:00</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>
  </div>
</template>

<script>
import { utils, read, writeFile, readFile } from "xlsx";
//早上9点之前都可以 晚上六点之前都可以,
//十点:9.40 - 10.30 下午三点 2.40-3.30
//地点只要是 北京市海淀区四季青镇北坞村路甲25号四季慧谷国家网络安全产业园的就是 属于公司打卡
import moment from "moment";
import draggable from "vuedraggable";
export default {
  data() {
    return {
      data: [],
      nameNewMap: {},
      dateMap: {},
      marketArr: [
        "陈晓东",
        "王钧",
        "罗宽",
        "田若愚",
        "庞依婷",
        "许艳飞",
        "马钧",
        "吴云鹤",
      ], //市场人员
      centerArr: [
        "孙慧芳",
        "张璇",
        "潘焰生",
        "王南南",
        "李文静",
        "刘艳",
        "吴琳琳",
        "周文侠",
      ],
      arrtwoCard: ["陈晓东", "王钧", "罗宽", "田若愚", "吴琳琳", "周文侠"], //打两次卡的人
      fireArr: ["吴琳琳"],
      endArr: [], //处理完的值
      timeForm: {
        date: "11月15日",
        name: "北京考勤每日打卡统计2023年11月",
      },
      company: ["四季慧谷国家网络安全产业园"],
    };
  },
  components: {
    draggable,
  },
  methods: {
    change(file) {
      this.data = [];
      console.log(file);
      let _file = file.raw;
      _file.arrayBuffer().then((res) => {
        let workbook = readFile(res);
        let sheet_name_list = workbook.SheetNames;
        let sheet = workbook.Sheets[sheet_name_list[0]];
        // 将该sheet转换为json数组1
        let arr = utils.sheet_to_json(sheet, {
          header: [
            "姓名",
            "考勤组",
            "部门",
            "工号",
            "职位",
            "UserId",
            "考勤日期",
            "考勤时间",
            "打卡时间",
            "打卡结果",
            "打卡地址",
            "打卡备注",
            "异常打卡原因",
            "打卡图片1",
            "打卡图片2",
            "打卡设备",
            "管理员修改备注",
            "管理员修改备注图片1",
            "管理员修改备注图片2",
            "管理员修改备注图片3",
          ],
        });
        //删除没用的前三行
        arr.splice(0, 1);
        arr.splice(0, 1);
        arr.splice(0, 1);
        this.data = arr;
        console.log(arr);
        this.handleData();
      });
    },

    //数据分类
    handleData() {
      this.dateMap = {};
      this.nameNewMap = {};
      this.data.forEach((item) => {
        if (this.nameNewMap[item["姓名"]]) {
          this.nameNewMap[item["姓名"]].push(item);
        } else {
          this.nameNewMap[item["姓名"]] = [item];
        }
      });
      console.log(this.nameNewMap);
      for (let key in this.nameNewMap) {
        let dateTime = this.nameNewMap[key].map((it) => {
          return {
            打卡时间: moment(it["打卡时间"]).format("YYYY-MM-DD HH:mm:ss"),
            打卡地址: it["打卡地址"],
          };
        });
        let uniqueData = [
          ...new Set(dateTime.map((item) => item["打卡时间"])),
        ].map((time) => {
          return dateTime.find((item) => item["打卡时间"] === time);
        });
        this.dateMap[key] = uniqueData;
      }

      console.log(this.dateMap);
      let arr = [];

      this.marketArr.forEach((item) => {
        this.setValue(arr, item);
      });
      this.centerArr.forEach((item) => {
        this.setValue(arr, item);
      });
      this.endArr = arr;
      this.createDom(this.endArr);
    },
    setValue(arr, item) {
      if (this.dateMap[item]) {
        let obj = this.getCardMsg(this.dateMap[item]);
        //不属于打两次卡的人
        if (!this.arrtwoCard.includes(item)) {
          arr.push({
            name: item,
            ...obj,
          });
        }
        //打两次卡的人
        else {
          obj.time2 = "/";
          obj.time3 = "/";
          arr.push({
            name: item,
            ...obj,
          });
        }
      } else {
        if (item == "王钧") {
          arr.push({
            name: item,
            time1: "未打卡",
            time2: "/",
            time3: "/",
            time4: "未打卡",
          });
          return;
        }
        if (this.fireArr.includes(item)) {
          arr.push({
            name: item,
            time1: "离职",
            time2: "离职",
            time3: "离职",
            time4: "离职",
          });
        } else {
          arr.push({
            name: item,
            time1: "请假",
            time2: "请假",
            time3: "请假",
            time4: "请假",
          });
        }
      }
    },
    //获取打卡信息
    getCardMsg(arr) {
      let obj = {
        time1: "未打卡",
        time2: "未打卡",
        time3: "未打卡",
        time4: "未打卡",
      };

      arr.forEach((item) => {
        let time = moment(item["打卡时间"]).format("HH:mm:ss");

        if (time <= "09:00:00") {
          this.handleTimeAddress(obj, item, "time1");
        }
        if (time > "09:00:00" && time <= "12:00:00") {
          this.handleTimeAddress(obj, item, "time2");
        }
        if (time > "14:00:00" && time < "18:00:00") {
          this.handleTimeAddress(obj, item, "time3");
        }
        if (time >= "18:00:00") {
          this.handleTimeAddress(obj, item, "time4");
        }
      });
      return obj;
    },
    //结果处理
    handleTimeAddress(obj, item, time) {
      if (this.isCompany(item["打卡地址"])) {
        obj[time] = "公司打卡";
      } else {
        obj[time] = item["打卡地址"]
          ? item["打卡地址"].split("经纬")[0]
          : "八成是补卡";
      }
    },
    //是否在公司
    isCompany(str) {
      let bool = false;
      if (!str) return false;
      for (let i = 0; i < this.company.length; i++) {
        if (str.includes(this.company[i])) {
          bool = true;
          break;
        }
      }
      return bool;
    },
    //渲染dom
    createDom(arr) {
      let tbody = document.querySelector("tbody");
      arr.forEach((item, index) => {
        if (index == 0) {
          let tr = document.createElement("tr");
          tr.innerHTML = `
          <td>${index + 1}</td>
          <td rowspan="8">市场,售前</td>
          <td>${item.name}</td>
          <td>${item.time1}</td>
          <td>${item.time2}</td>
          <td>${item.time3}</td>
          <td>${item.time4}</td>
        `;
          tbody.append(tr);
        } else if (index == 8) {
          let tr = document.createElement("tr");
          tr.innerHTML = `
          <td>${index + 1}</td>
          <td rowspan="${this.centerArr.length}">北京中心</td>
          <td>${item.name}</td>
          <td>${item.time1}</td>
          <td>${item.time2}</td>
          <td>${item.time3}</td>
          <td>${item.time4}</td>
        `;
          tbody.append(tr);
        } else {
          let tr = document.createElement("tr");
          tr.innerHTML = `
          <td>${index + 1}</td>
          <td>${item.name}</td>
          <td>${item.time1}</td>
          <td>${item.time2}</td>
          <td>${item.time3}</td>
          <td>${item.time4}</td>
        `;
          tbody.append(tr);
        }
      });
      //表格导出文件
    },
    async exportFile() {
      let tbody = document.querySelector("tbody");
      if (!tbody.innerHTML) {
        this.$message({
          message: "先上传表再导出",
          type: "warn",
        });
        return;
      }
      localStorage.setItem("timeForm", JSON.stringify(this.timeForm));
      localStorage.setItem("marketArr", JSON.stringify(this.marketArr));
      localStorage.setItem("company", JSON.stringify(this.company));
      localStorage.setItem("centerArr", JSON.stringify(this.centerArr));
      localStorage.setItem("arrtwoCard", JSON.stringify(this.arrtwoCard));
      localStorage.setItem("fireArr", JSON.stringify(this.fireArr));
      await this.$nextTick();
      let dom = document.querySelector("table");
      const sheet = utils.table_to_sheet(dom);
      const wb = utils.book_new();
      utils.book_append_sheet(wb, sheet, "sheet1");
      writeFile(wb, this.timeForm.name + ".xlsx");
    },
    clear() {
      let tbody = document.querySelector("tbody");
      tbody.innerHTML = null;
    },
    addCompany() {
      this.prompt("属于公司地点", "company");
    },
    addMarket() {
      this.prompt("市场人员", "marketArr");
    },

    addCenter() {
      this.prompt("中心人员", "centerArr");
    },
    addFire() {
      this.prompt("离职人员", "fireArr");
    },
    addTwo() {
      this.prompt("只需要打两次卡的人", "arrtwoCard");
    },
    prompt(str, arr) {
      this.$prompt(`请输入${str}`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(({ value }) => {
        if (value) {
          this[arr].push(value);
          localStorage.setItem(arr, JSON.stringify(this[arr]));
        } else {
          this.$message({
            message: "周大宝你倒是输入个值",
            type: "warn",
          });
        }
      });
    },
    deleteCompany(index) {
      this.deleteEvent(index, "company");
    },
    deleteMarket(index) {
      this.deleteEvent(index, "marketArr");
    },
    deleteCenter(index) {
      this.deleteEvent(index, "centerArr");
    },
    deleteFire(index) {
      this.deleteEvent(index, "fireArr");
    },
    deleteArrtwoCard(index) {
      this.deleteEvent(index, "arrtwoCard");
    },
    deleteEvent(index, arr) {
      if (arr == "company") {
        if (this.company.length > 1) {
          this.company.splice(index, 1);
        } else {
          this.$message({
            message: "周大宝你至少留一个吧",
            type: "warn",
          });
        }
      } else {
        this[arr].splice(index, 1);
      }
      localStorage.setItem(arr, JSON.stringify(this[arr]));
    },
  },
  mounted() {
    let local = localStorage;
    let { timeForm, company, marketArr, centerArr, arrtwoCard, fireArr } =
      local;
    if (timeForm) this.timeForm = JSON.parse(timeForm);
    if (company) this.company = JSON.parse(company);
    if (marketArr) this.marketArr = JSON.parse(marketArr);
    if (centerArr) this.centerArr = JSON.parse(centerArr);
    if (arrtwoCard) this.arrtwoCard = JSON.parse(arrtwoCard);
    if (fireArr) this.fireArr = JSON.parse(fireArr);
  },
};
</script>

<style lang="less" scoped>
.upload {
  width: 100%;
  height: 100%;
  overflow: auto;
}
.box {
  display: flex;
  flex-wrap: wrap;
}
table {
  border-collapse: collapse;
  margin-top: 10px;
}
tr,
th {
  width: 150px;
  height: 40px;
  text-align: center;
  line-height: 40px;
  border: 1px solid black;
}
/deep/ td {
  width: 150px;
  text-align: center;
  line-height: 30px;
  border: 1px solid black;
}
.upload-demo {
  width: 360px;
}
/deep/ .input .el-input {
  width: 300px;
}

.type {
  margin-left: 20px;
  padding: 10px;
  background-color: #fff;
  width: 300px;
  margin-bottom: 20px;
}

.type .div {
  display: flex;
  box-sizing: border-box;
  justify-content: space-between;
  line-height: 30px;
}

.type .div p {
  width: 30px;
  height: 30px;
}
.type .div p i {
  margin-left: 5px;
  cursor: pointer;
}
header {
  font-weight: 600;
  font-size: 18px;
  margin-bottom: 20px;
}
</style>
